<template>
  <div class="myworks-container">
    <div class="header">
      <h1>我的作品</h1>
      <el-button class="gradient-btn" @click="$router.push('/create')">
        <el-icon><Plus /></el-icon>
        新建作品
      </el-button>
      <el-button class="gradient-btn" @click="$router.push('/gallery')">
        返回广场
      </el-button>
    </div>

    <!-- 加载状态 -->
    <el-alert 
      v-if="isLoading" 
      title="正在加载您的作品..." 
      type="info" 
      :closable="false" 
      class="status-alert"
    />
    
    <!-- 加载错误提示 -->
    <el-alert 
      v-if="loadError" 
      title="加载作品失败，请稍后重试" 
      type="error" 
      :closable="true" 
      class="status-alert"
      @close="loadError = false"
    />

    <div v-if="!isLoading && works.length === 0" class="empty-state">
      <div class="empty-content">
        <el-icon class="empty-icon"><Picture /></el-icon>
        <h2>暂无作品</h2>
        <p>开始您的第一个AI创作吧</p>
        <el-button class="gradient-btn" @click="$router.push('/create')">
          开始创作
        </el-button>
        
        <div class="ai-assistant glass-card">
          <h3>AI灵感助手</h3>
          <p>试试生成「赛博朋克 Tokyo 雨夜」？</p>
          <el-button size="small" class="gradient-btn" @click="applySuggestion">
            点击直接填入提示词
          </el-button>
        </div>
      </div>
    </div>

    <div v-else-if="!isLoading" class="works-grid">
      <el-card 
        v-for="(work, index) in works" 
        :key="work.id || index" 
        class="work-card hover-card"
        :body-style="{ padding: '0' }"
        @click="openWorkDetail(work)"
      >
        <div class="work-image">
          <img :src="work.image_url" :alt="work.title" />
        </div>
        <div class="work-info">
          <h3>{{ work.title }}</h3>
          <p class="work-date">{{ formatDate(work.createdAt) }}</p>
          <div class="work-tags">
            <el-tag
              v-for="(tag, tagIndex) in work.tags"
              :key="tagIndex"
              size="small"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 作品详情弹窗 - 用于查看、编辑和删除作品 -->
    <el-dialog
      v-model="showDetail"
      :title="currentWork ? `作品详情: ${currentWork.title}` : '作品详情'"
      :width="isMobile ? '90%' : '700px'"
      :before-close="handleClose"
    >
      <div v-if="currentWork" class="work-detail">
        <div class="detail-image">
          <img :src="currentWork.image_url" :alt="currentWork.title" />
        </div>
        
        <div class="detail-info">
          <h2>{{ currentWork.title }}</h2>
          
          <div class="detail-meta">
            <p><strong>创建日期:</strong> {{ formatDate(currentWork.createdAt) }}</p>
            <p><strong>状态:</strong> {{ currentWork.status || '已完成' }}</p>
          </div>
          
          <div class="detail-tags">
            <strong>标签:</strong>
            <el-tag
              v-for="(tag, tagIndex) in currentWork.tags"
              :key="tagIndex"
              size="small"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
          
          <div class="detail-description">
            <strong>描述:</strong>
            <p>{{ currentWork.description || '无描述信息' }}</p>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleDownload">下载作品</el-button>
        <el-button type="danger" @click="handleDelete">删除作品</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture, Edit, Download, Delete } from '@element-plus/icons-vue'

const router = useRouter()
const works = ref([])
const isLoading = ref(true)  // 加载状态
const loadError = ref(false) // 加载错误状态
const showDetail = ref(false) // 控制作品详情弹窗显示
const currentWork = ref(null) // 当前选中的作品
const isMobile = ref(false)   // 判断是否为移动设备

// 页面加载前检查设备类型
onBeforeMount(() => {
  checkDeviceType()
  window.addEventListener('resize', checkDeviceType)
})

// 检查设备类型
const checkDeviceType = () => {
  isMobile.value = window.innerWidth < 768
}

// 页面加载时获取我的作品
onMounted(() => {
  fetchMyWorks()
})

// 从后端API获取我的作品
const fetchMyWorks = async () => {
  try {
    isLoading.value = true
    loadError.value = false
    
    const response = await fetch('http://localhost:3000/api/mywork', {
      method: 'GET',
      credentials: 'include',  // 携带登录状态cookie
      headers: {
        'Content-Type': 'application/json'
      },
      timeout: 5000
    })
    
    if (!response.ok) {
      // 未登录或权限不足时跳转登录页
      if (response.status === 401) {
        ElMessage.warning('请先登录查看您的作品')
        router.push('/login')
        return
      }
      throw new Error(`请求失败: ${response.status}`)
    }
    
    const result = await response.json()
    
    // 假设后端返回格式: { success: true, data: [...] }
    if (result.success && Array.isArray(result.data)) {
      works.value = result.data
    } else {
      works.value = []
    }
  } catch (error) {
    console.error('加载我的作品失败:', error)
    loadError.value = true
    works.value = []
  } finally {
    isLoading.value = false
  }
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return '未知日期'
  try {
    return new Date(date).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    return date.toString().slice(0, 10)
  }
}

// 应用灵感提示
const applySuggestion = () => {
  router.push({
    path: '/create',
    query: { prompt: '赛博朋克 Tokyo 雨夜，霓虹灯光，未来城市，4K高清' }
  })
}

// 打开作品详情弹窗
const openWorkDetail = (work) => {
  currentWork.value = { ...work } // 复制作品数据
  showDetail.value = true
}

// 关闭弹窗
const handleClose = () => {
  showDetail.value = false
  currentWork.value = null
}

// 下载作品
const handleDownload = async () => {
  if (!currentWork.value) return
  
  try {
    // 调用后端下载接口
    const response = await fetch(`http://localhost:3000/api/works/${currentWork.value.id}/download`, {
      method: 'POST',
      credentials: 'include'
    })
    
    if (!response.ok) throw new Error('下载失败')
    
    // 处理文件下载
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${currentWork.value.title || '我的作品'}.jpg`
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
    
    ElMessage.success(`开始下载: ${currentWork.value.title}`)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请稍后重试')
  }
}

// 删除作品
const handleDelete = async () => {
  if (!currentWork.value) return
  
  ElMessageBox.confirm(
    `确定要删除作品「${currentWork.value.title}」吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        // 调用后端删除接口
        const response = await fetch(`http://localhost:3000/api/work-del/${currentWork.value.id}`, {
          method: 'GET',
          credentials: 'include'
        })
        
        if (!response.ok) throw new Error('删除失败')
        
        // 更新本地列表
        works.value = works.value.filter(w => w.id !== currentWork.value.id)
        ElMessage.success('删除成功')
        
        // 关闭弹窗
        handleClose()
      } catch (error) {
        console.error('删除作品失败:', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}
</script>

<style lang="scss" scoped>
.myworks-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #121212;
  
  .status-alert {
    margin-bottom: 20px;
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    
    h1 {
      background: linear-gradient(90deg, #7B2CFF, #C76EFF);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }
  
  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60vh;
    
    .empty-content {
      text-align: center;
      
      .empty-icon {
        font-size: 4rem;
        color: #7B2CFF;
        margin-bottom: 20px;
      }
      
      h2 {
        margin-bottom: 10px;
        color: #f8f8f8;
      }
      
      p {
        color: #aaa;
        margin-bottom: 20px;
      }
      
      .ai-assistant {
        margin-top: 30px;
        padding: 20px;
        max-width: 400px;
        
        h3 {
          margin-bottom: 10px;
          color: #C76EFF;
        }
        
        p {
          margin-bottom: 15px;
        }
      }
    }
  }
  
  .works-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 25px;
    
    .work-card {
      overflow: hidden;
      border-radius: 12px;
      background: rgba(248, 248, 248, 0.05);
      cursor: pointer;
      transition: transform 0.3s ease, box-shadow 0.3s ease;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
      }
      
      .work-image {
        position: relative;
        height: 250px;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.5s ease;
        }
        
        &:hover img {
          transform: scale(1.05);
        }
      }
      
      .work-info {
        padding: 15px;
        
        h3 {
          margin-bottom: 5px;
          color: #f8f8f8;
        }
        
        .work-date {
          color: #aaa;
          margin-bottom: 10px;
          font-size: 0.9rem;
        }
        
        .work-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 5px;
          
          .el-tag {
            background: rgba(123, 44, 255, 0.2);
            color: #C76EFF;
            border: none;
          }
        }
      }
    }
  }
  
  .gradient-btn {
    background: linear-gradient(90deg, #7B2CFF, #C76EFF);
    color: white;
    border: none;
    border-radius: 24px;
    
    &:hover {
      background: linear-gradient(90deg, #6A1FFF, #B65EFF);
      color: white;
      box-shadow: 0 4px 12px rgba(123, 44, 255, 0.4);
    }
  }
  
  // 作品详情弹窗样式
  .work-detail {
    display: flex;
    flex-direction: column;
    gap: 20px;
    
    @media (min-width: 768px) {
      flex-direction: row;
    }
    
    .detail-image {
      flex: 1;
      border-radius: 8px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: auto;
        object-fit: cover;
        border-radius: 8px;
      }
    }
    
    .detail-info {
      flex: 1;
      padding: 0 10px;
      
      h2 {
        color: #f8f8f8;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #333;
      }
      
      .detail-meta {
        margin-bottom: 20px;
        color: #ddd;
        
        p {
          margin: 8px 0;
        }
      }
      
      .detail-tags {
        margin-bottom: 20px;
        padding: 10px 0;
        
        strong {
          color: #ddd;
          margin-right: 10px;
        }
        
        .tag-item {
          margin-right: 5px;
          margin-bottom: 5px;
        }
      }
      
      .detail-description {
        color: #bbb;
        
        strong {
          color: #ddd;
          display: block;
          margin-bottom: 10px;
        }
        
        p {
          line-height: 1.6;
          background: rgba(255, 255, 255, 0.05);
          padding: 10px;
          border-radius: 4px;
        }
      }
    }
  }
}
</style>
